#include "logcplus_debug_util.h"
#include "logcplus_fileutil.h"

#include <fstream>
using namespace std;

namespace logcplus
{
    #define maxBufferSize       8192

    static char logcplus_name [60] = {0};
    static int 	debug_print_tofile(  int nLevel, const char* sLogBuf);
    static int 	clean_print_tofile(int nLevel, const char* sLogBuf);  

    void logcplus_init_debug()
    {
        logcplus_util::get_procname_pid(getpid(),logcplus_name);
    }

    int 	debug_print_tofile(int nLevel, const char* sLogBuf)
    {
        char debugFile[256] = {0};
        sprintf(debugFile,"%s/log/%s",getenv("HOME"),"logcplus.log");
        static std::ofstream fs(debugFile,ofstream::out | ofstream::app);
        //FileUtil::appendFile(debugFile,sLogBuf,strlen(sLogBuf));
        if(!fs.is_open())
        {
            printf("open ofstream failed.\n");
            return -1;
        }
        
        fs << sLogBuf;
        fs.flush();
        return 0;
    }

    int 	clean_print_tofile(int nLevel, const char* sLogBuf)
    {
        char debugFile[256] = {0};
        sprintf(debugFile,"%s/log/%s",getenv("HOME"),"logclean.log");
        static std::ofstream fs(debugFile,ofstream::out | ofstream::app);
        if(!fs.is_open())
        {
            printf("open ofstream failed.\n");
            return -1;
        }
        fs << sLogBuf;
        fs.flush();
        return 0;
    }

    void logcplus_debug_print(const char* File, const char* Function,const int Line, int Level,const char* Fmt, ...)
    {
        static const char* psEnvDebug = getenv(LOGCPLUS_DEBUG_LEVEL);
        if(!psEnvDebug)
        {
            psEnvDebug = "INFO";
        }
        if ( Level >= logcplus_loglevl_cvt(psEnvDebug) )
        {
            char LogMsg[maxBufferSize]={0};
            FORMAT_ARGS(LogMsg,Fmt);

            char sLogFmtBuf[1024]={0};	
            logcplus_layout logLayout("%D{YYYY/MM/DD hhmmss}:%5T:%6P:%18F:%4L:");
            logLayout.formatLayout(File,Function,Line,Level,sLogFmtBuf);	

            char sLogText[maxBufferSize]={0};
            snprintf(sLogText,sizeof(sLogText)-1,"%s%14.14s:%s\n",sLogFmtBuf,logcplus_name,LogMsg);
            debug_print_tofile(Level,sLogText);
        }
        return;
    }	 

    void logcplus_clean_print(const char* File, const char* Function,const int Line, int Level,const char* Fmt, ...)
    {
        char LogMsg[maxBufferSize]={0};
        FORMAT_ARGS(LogMsg,Fmt);

        char sLogFmtBuf[1024]={0};	
        logcplus_layout logLayout("%D{YYYYMMDDhhmmss}:%6P:%4L:");
        logLayout.formatLayout(File,Function,Line,Level,sLogFmtBuf);	

        char sLogText[maxBufferSize]={0};
        snprintf(sLogText,sizeof(sLogText)-1,"%s:%s\n",sLogFmtBuf,LogMsg);

        clean_print_tofile(Level,sLogText);
        return;
    }    

}